﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WXY.Course.BLL;
using WXY.Course.Model;
using WXY.Course.Web.Areas.Admin.Filter;

namespace WXY.Course.Web.Areas.Admin.Controllers
{
    [DefaultAuthorize]
    public class NoticeController : Controller
    {
        private NoticeBLL _noticeBLL = new NoticeBLL();

        public ActionResult List()
        {
            var list = _noticeBLL.GetList();
            return View(list);
        }


        public ActionResult Edit(int? id)
        {
            if (id.HasValue)
            {
                var info = _noticeBLL.Get(id.Value);
                return View(info);
            }
            return View();
        }

        [HttpPost]
        public ActionResult Edit(NoticeInfo notice)
        {
            if (!ModelState.IsValid)
            {
                return View(notice);
            }
            bool editResult = DoEdit(notice) > 0;

            if (editResult)
            {
                return RedirectToAction("List");
            }
            return View(notice);
        }

        private int DoEdit(NoticeInfo notice)
        {
            UserInfo userInfo = HttpContext.Items["UserInfo"] as UserInfo;
            notice.UpdateUser = userInfo;

            int editResult = 0;
            if (notice.Code.HasValue)
            {
                editResult = _noticeBLL.Update(notice);
            }
            else
            {
                editResult = _noticeBLL.Insert(notice);
            }
            return editResult;
        }

        [HttpPost]
        [JsonExceptionFilter(typeof(NoticeController), JsonRequestBehavior.AllowGet)]
        public JsonResult Delete(int id)
        {
            var result = new BoolResult<int>
            {
                IsSuccess = true,
                Data = _noticeBLL.Delete(id)
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [JsonExceptionFilter(typeof(NoticeController), JsonRequestBehavior.AllowGet)]
        public JsonResult Active(int id)
        {
            var result = new BoolResult<int>
            {
                IsSuccess = true,
                Data = _noticeBLL.Active(id)
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
